package com.dc.bobaoge.project.v2.to.v3.business.core;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dc.bobaoge.base.entity.message.common.po.MessageCount;
import com.dc.bobaoge.base.mapper.core.ChannelMapper;
import com.dc.bobaoge.base.mapper.message.MessageCountMapper;
import com.dc.bobaoge.common.base.entity.message.business.BaseMessageBusinessPo;
import com.dc.bobaoge.common.constant.ConstantMq;
import com.dc.bobaoge.common.util.YearQuarterUtil;
import com.dc.bobaoge.project.base.core.now.service.ZoneService;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreMessageMapper;
import com.dc.bobaoge.project.base.core.util.MessageCommonUtil;
import com.dc.bobaoge.project.v2.to.v3.business.core.method.message.AbstractResolveMessageMethod;
import com.dc.bobaoge.project.v2.to.v3.business.core.method.user.UserResolveMethod;
import com.own.business.sync.trigger.base.common.TypeConstant;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import com.own.business.sync.trigger.base.method.ResolveMethod;
import com.own.component.common.exception.BusinessSimpleException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MessageResolveMethod
 *
 * @author chenxueli
 * @date 2023-12-22 11:00:00
 */
@Slf4j
@Component
public class MessageResolveMethod implements ResolveMethod {


    private static final Map<String, AbstractResolveMessageMethod<? extends BaseMessageBusinessPo, ? extends BaseMapper<?>>> RESOLVE_MESSAGE_FUNCTION_MAP = new HashMap<>();

    @Resource
    private List<AbstractResolveMessageMethod<? extends BaseMessageBusinessPo, ? extends BaseMapper<?>>> abstractResolveMessageMethodList;
    @Resource
    private MessageCountMapper messageCountMapper;
    @Resource
    private ChannelMapper channelMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OldCoreMessageMapper oldCoreMessageMapper;
    @Resource
    private UserResolveMethod userResolveMethod;
    @Resource
    private MessageCommonUtil messageCommonUtil;

    @Resource
    private ZoneService zoneService;

    @PostConstruct
    private void init() {
        // 处理
        abstractResolveMessageMethodList.forEach(item -> {
            RESOLVE_MESSAGE_FUNCTION_MAP.put(item.getMessageTemplate().getType(), item);
        });
    }

    /**
     * 修改的处理方法
     *
     * @param trigger 日志信息
     */
    @Override
    public void update(SyncTrigger trigger) {
        // 查询旧表的数据
        var oldCoreMessage = oldCoreMessageMapper.selectById(trigger.getTargetId());
        if (oldCoreMessage == null) {
            throw new BusinessSimpleException("信息不存在:" + trigger.getTargetId());
        }
        // 获取季度信息
        var quarter = YearQuarterUtil.get(oldCoreMessage.getMessageDate());
        // 获取简单的一些消息信息数据
        var simple = messageCommonUtil.getSimple(oldCoreMessage);
        var detail = messageCommonUtil.getDetail(oldCoreMessage);
        // 查询对应的频道
        var channel = channelMapper.selectById(detail.getChannelId());
        if (channel != null) {
            simple.setChannelName(channel.getName());
            detail.setChannelName(channel.getName());
        }
        // 获取商圈的信息
        var zone = zoneService.getById(detail.getZoneId());
        var templateType = simple.getType();
        // 获取该信息的具体处理方式
        var method = RESOLVE_MESSAGE_FUNCTION_MAP.get(templateType);
        // 获取用户的信息
        var userInfo = userResolveMethod.getByUserId(oldCoreMessage.getMessageUserId());
        // 执行具体的方案
        var newItem = method.resolve(trigger.getTargetId(), quarter, oldCoreMessage, item -> {
            // 设置基础信息
            item.setFkZoneId(detail.getZoneId());
            item.setRfZoneName(detail.getZoneName());
            item.setFkChannelId(detail.getChannelId());
            item.setRfChannelName(detail.getChannelName());
            item.setFkTitleId(detail.getTitleId());
            item.setRfTitleName(detail.getTitleName());
            // 设置用户的一些信息
            if (userInfo.value1() != null) {
                item.setRfUserName(userInfo.value1().getName());
            }
            if (userInfo.value2() != null) {
                item.setFkContactUserId(userInfo.value2().getId());
                item.setRfContactPhone(userInfo.value2().getPhone());
            }
            // 设置经纬度信息
            item.setLatitude(zone.getLatitude());
            item.setLongitude(zone.getLongitude());
            item.setZoneLatitude(zone.getLatitude());
            item.setZoneLongitude(zone.getLongitude());
            // 设置分表信息
            item.setSharding(quarter);
            item.setIsVip(0);
        }, item -> {
            // 设置基础信息
            item.setFkZoneId(detail.getZoneId());
            item.setRfZoneName(detail.getZoneName());
            item.setFkChannelId(detail.getChannelId());
            item.setRfChannelName(detail.getChannelName());
            item.setFkTitleId(detail.getTitleId());
            item.setRfTitleName(detail.getTitleName());
            // 设置用户的一些信息
            if (userInfo.value1() != null) {
                item.setRfUserName(userInfo.value1().getName());
            }
            if (userInfo.value2() != null) {
                item.setFkContactUserId(userInfo.value2().getId());
                item.setRfContactPhone(userInfo.value2().getPhone());
            }
            // 设置经纬度信息
            item.setZoneLatitude(zone.getLatitude());
            item.setZoneLongitude(zone.getLongitude());
        });
        // 判断信息
        if (trigger.getOldStatus() != null && trigger.getOldStatus() == 0 && trigger.getNewStatus() != null && trigger.getNewStatus() == 1) {
            resolveAfterAuditPass(oldCoreMessage.getMessageId(), templateType, quarter, simple.getTitleId());
        }
        // 添加对应的总数信息
        if (trigger.getType() == TypeConstant.INSERT) {
            // 去查询是否存在
            var tempWrapper = new LambdaQueryWrapper<MessageCount>()
                    .eq(MessageCount::getFkMessageId, oldCoreMessage.getMessageId())
                    .eq(MessageCount::getType, templateType)
                    .eq(MessageCount::getQuarter, quarter);
            var count = messageCountMapper.selectCount(tempWrapper);
            // 如果不存在则添加
            if (count == 0) {
                var messageCount = new MessageCount();
                messageCount.setType(templateType);
                messageCount.setQuarter(quarter);
                messageCount.setFkMessageId(oldCoreMessage.getMessageId());
                // 去查询总数表
                messageCountMapper.insert(messageCount);
            }
        }
        if (newItem.getIsDeleted() == 1) {
            // 执行删除搜索引擎的数据
            rabbitTemplate.send(ConstantMq.MESSAGE_ELASTIC_SYNC_DELETE_EXCHANGE, "", MessageBuilder
                    .withBody((newItem.getId() + "").getBytes(StandardCharsets.UTF_8))
                    .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                    .build());
        }
    }

    /**
     * 审批通过后的处理方法
     *
     * @param messageId    消息id
     * @param templateType 模板信息
     * @param quarter      季度信息
     * @param titleId      标题id
     */
    private void resolveAfterAuditPass(Long messageId, String templateType, String quarter, Long titleId) {
        //  审批成功发送给客户端服务器消费
        var entity = new MessagePublishAfterEntity();
        entity.setId(messageId);
        entity.setQuarter(quarter);
        entity.setType(templateType);
        entity.setTitleId(titleId);
        rabbitTemplate.send(ConstantMq.MESSAGE_PUBLISH_AFTER_EXCHANGE, "", MessageBuilder
                .withBody(JSON.toJSONString(entity).getBytes(StandardCharsets.UTF_8))
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .build());
    }

    /**
     * 名称信息
     *
     * @return 名称
     */
    @Override
    public String name() {
        return "message";
    }

    @Data
    public static class MessagePublishAfterEntity implements Serializable {

        /**
         * 消息id
         */
        private Long id;

        /**
         * 消息类型
         */
        private String type;

        /**
         * 季度信息
         */
        private String quarter;

        /**
         * 标题id
         */
        private Long titleId;

    }

}
